<?php
/**
 * Created by PhpStorm.
 * User: Sergey
 * Date: 24.02.14
 * Time: 0:03
 */

include_once BASE_DQ_PLUGIN_PATH . "classes/UserDao.php";
include_once BASE_DQ_PLUGIN_PATH . "classes/GroupDao.php";

$userDao = new UserDao();
$groupDao = new GroupDao();

if (isset($_REQUEST["userId"]) && intval($_REQUEST["userId"]) > 0) {
    $userId = intval($_REQUEST["userId"]);
    $user = $userDao->getById($userId, UserDao::ROLE_TUTOR);
    $user->groups = isset($_REQUEST["groups"]) ? $_REQUEST["groups"] : array();
    $userDao->edit($user, UserDao::ROLE_TUTOR);

    header(
        "Location: " . menu_page_url("distant-quiz/admin.php", false) .
        "#tutors"
    );
}

$tutors = $userDao->getAll(UserDao::ROLE_TUTOR);
$groups = $groupDao->getAll();
?>

<table class="wp-list-table widefat fixed posts tutor-table">
    <thead>
    <tr>
        <th>Id</th>
        <th>Имя</th>
        <th>Доступные группы</th>
    </tr>
    </thead>
    <tbody>
    <? foreach ($tutors as $tutor) { ?>
        <tr>
            <td><?= $tutor->id ?></td>
            <td><?= $tutor->displayName ?></td>
            <td>
                <? if (count($tutor->groups) > 0) { ?>
                    <? foreach ($tutor->groups as $groupId) { ?>
                        <span class="group-lbl"
                              title="Нажмите левой кнопкой мыши чтоб редактировать">
                            <?= $groupDao->getById($groupId)->name ?>
                        </span><br>
                    <? } ?>
                <? } else { ?>
                    <span class="group-lbl"
                          title="Нажмите левой кнопкой мыши чтоб редактировать">&lt;-- Нет --&gt;</span>
                <? } ?>
                <form method="post">
                    <input type="hidden"
                           name="userId"
                           value="<?= $tutor->id ?>"/>
                    <select name="groups[]" multiple
                            title="Удерживайте Ctrl и выделите группы. Для сохранения нажмите мышью за пределами списка."
                            size="8"
                            style="display: none;">
                        <? foreach ($groups as $group) { ?>
                            <option value="<?= $group->id ?>"
                                <?= in_array($group->id, $tutor->groups) ? "selected" : "" ?>>
                                <?= $group->name ?>
                            </option>
                        <? } ?>
                    </select>
                </form>
            </td>
        </tr>
    <? } ?>
    </tbody>
</table>